package com.adams.common;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.context.SecurityContextHolder;
import org.springframework.security.userdetails.UserDetails;

import com.adams.access.db.bean.OptLog;
import com.adams.access.db.bean.ViewEvent;
import com.adams.log.service.OptLogService;
import com.adams.security.dao.VASUser;
import com.adams.utils.Page;
import com.adams.utils.SpringBeanFactoryUtil;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 
 * 
 * File Name : BaseAction.java
 * 
 * @Description : Action的基类
 * @author 902990封文进
 */
public class BaseAction extends ActionSupport implements ServletRequestAware,
		ServletResponseAware
{

	private static Logger logger = LoggerFactory.getLogger(BaseAction.class);

	private static final long serialVersionUID = 1L;

	protected HttpServletRequest request;

	protected HttpServletResponse response;

	protected int pageNo = 1;// 页次

	protected int pageSize = 10; // 每页大小，默认显示10条记录

	public void setServletRequest(HttpServletRequest request)
	{
		this.request = request;
	}

	public void setServletResponse(HttpServletResponse response)
	{
		this.response = response;

	}

	/**
	 * 
	 * Description : 获取分页
	 * 
	 * @return Page
	 * 
	 */
	@SuppressWarnings("unchecked")
	public Page getPage()
	{
		Page page = new Page();
		String start = request.getParameter("start");
		String limit = request.getParameter("limit");
		if (StringUtils.isNotEmpty(start))
		{
			page.setBeginCount(Integer.parseInt(start));
		}
		if (StringUtils.isNotEmpty(limit))
		{
			page.setPageSize(Integer.parseInt(limit));
		}
		return page;
	}

	/**
	 * 
	 * Description : 对遗留系统 传参的处理（pageNo，pageSize）
	 * 
	 * @return
	 * 
	 */
	@SuppressWarnings("unchecked")
	public Page getPageOld()
	{
		Page page = new Page();
		page.setBeginCount(this.pageNo);
		page.setPageSize(this.pageSize);
		return page;
	}

	/**
	 * 
	 * Description : 创建日志
	 * 
	 * @param operateEvent
	 * @param operateContent
	 * 
	 */
	public void createLog(String operateEvent, String operateContent)
	{
		try
		{
			String event = EventProperties.getProperty(operateEvent);
			if (event != null)
			{
				OptLogService optLogService = (OptLogService) SpringBeanFactoryUtil
						.getBean("optLogService");

				OptLog log = new OptLog();
				log.setOperator(getUserName());
				log.setOperateEvent(event);
				log.setOperateContent(operateContent);
				log.setOperateFrom(request.getRemoteAddr());
				log.setOperateTime(DateFormatUtils.format(new Date(),
						"yyyy-MM-dd HH:mm:ss"));

				optLogService.createLog(log);
			}
		} catch (Exception e)
		{
			logger.error(e.getMessage(), e);
		}
	}

	/**
	 * 
	 * Description : 获取用户ID
	 * 
	 * @return int
	 * 
	 */
	public int getUserId()
	{
//		User user = Certificate.getUser(request);
//		if (user == null)
//		{
//			throw new RuntimeException(Constants.OVER_TIME);
//
//		} else
//		{
//			return user.getId().intValue();
//		}
		
		VASUser userDetails = (VASUser) SecurityContextHolder.getContext()
	    .getAuthentication()
	    .getPrincipal();
		
		if (userDetails == null)
		{
			throw new RuntimeException(Constants.OVER_TIME);

		} else
		{
			return userDetails.getUser().getId().intValue();
		}
		
//		return userDetails.getUser().getId().intValue();


	}

	
	/**
	 * 得到用户事件权限集合
	 * @return
	 */
	public Set<ViewEvent> getRoleEvents(){
	    VASUser userDetails = (VASUser) SecurityContextHolder.getContext()
        .getAuthentication()
        .getPrincipal();
	    return userDetails.getUser().getRole().getEvents();
	}
	
	
	/**
	 * 
	 * Description : 获取用户名
	 * 
	 * @return String
	 * 
	 */
	public String getUserName()
	{
		
		
		UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext()
	    .getAuthentication()
	    .getPrincipal();


	 return  userDetails.getUsername();

		
		
//		User user = Certificate.getUser(request);
//		if (user == null)
//		{
//			throw new RuntimeException(Constants.OVER_TIME);
//
//		} else
//		{
//			return user.getUserName();
//		}
	}

	/**
	 * 
	 * Description : 提示成功信息
	 * 
	 * @param message
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void sendSuccessMessage(String message)
	{
		Map result = new HashMap();
		result.put("success", true);
		result.put("msg", message);
		write(JSONObject.fromObject(result).toString());
	}

	/**
	 * 
	 * Description : 提示失败信息
	 * 
	 * @param message
	 * 
	 */
	@SuppressWarnings("unchecked")
	public void sendFailureMessage(String message)
	{
		Map result = new HashMap();
		result.put("failure", true);
		result.put("msg", message);
		write(JSONObject.fromObject(result).toString());
	}

	/**
	 * 
	 * Description : 输出内容
	 * 
	 * @param value
	 * 
	 */
	public void write(String value)
	{
		try
		{

			response.setContentType("text/html;charset=UTF-8");
			response.getWriter().write(value);
		} catch (IOException e)
		{
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 
	 * Description : 输出文件
	 * 
	 * @param value
	 * 
	 */
	public void writeExcelFile(InputStream is) {
		response.setContentType("application/x-download");
		DateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd");
		String fileName = dateFormat.format(new Date());
		/* 如果已经设置文件名 不再设置Excel文件的名称*/
		if (!response.containsHeader("Content-Disposition")) {
			response.setHeader("Content-Disposition", "attachment; filename=\""
					+ fileName+".xls" + "\"");
		}
		BufferedInputStream bis = null;
		BufferedOutputStream bos = null;
		try {
			ServletOutputStream out = response.getOutputStream();
			bis = new BufferedInputStream(is);
			bos = new BufferedOutputStream(out);
			byte[] buff = new byte[2048];
			int bytesRead;
			while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
				bos.write(buff, 0, bytesRead);
			}
		} catch (IOException e) {
			e.printStackTrace();
			throw new RuntimeException(e);
		} finally {
			if (bis != null)
				try {
					bis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			if (bos != null)
				try {
					bos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
		}
	}

	// public int getPageNo()
	// {
	// return pageNo;
	// }
	//
	// public void setPageNo(int pageNo)
	// {
	// this.pageNo = pageNo;
	// }
	//
	// public int getPageSize()
	// {
	// return pageSize;
	// }
	//
	// public void setPageSize(int pageSize)
	// {
	// this.pageSize = pageSize;
	// }
	public int getPageNo()
	{
		return pageNo;
	}

	public void setPageNo(int pageNo)
	{
		this.pageNo = pageNo;
	}

	public int getPageSize()
	{
		return pageSize;
	}

	public void setPageSize(int pageSize)
	{
		this.pageSize = pageSize;
	}
}
